<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1></h1>
    <form action="regist">
        <!-- <div>账号：<input type="text" name="username" class="name"></div>
        <div>账号：<input type="password" name="username" class="pwd"></div> -->
        <button class="login">登录</button>
        <!-- 显示提示 -->
        <h1></h1>
    </form>
    <script>
        let btn = document.querySelector(".login");
      btn.onclick= (e) => {
            e.preventDefault(); // 阻止默认form传递数据行为
            // let uname = document.querySelector(".name");
            // let upwd = document.querySelector(".pwd");
            // 1
            let xhr = new XMLHttpRequest(); // 实例化对象
            // 2
            xhr.onreadystatechange = () => {
                if (xhr.status == 200 && xhr.readyState == 4) {
                    console.log("是否成功", xhr.responseText);
                    //可以使用 JSON.parse() 方法将数据转换为 JavaScript 对象
                    const res = JSON.parse(xhr.responseText);
                    localStorage.setItem("token", res.token);
                    let h1 = document.querySelector('h1');
                    h1.innerText = res.nickname;
                    
                }
            };
            // 3
            xhr.open("POST", "http://localhost:8000/noauth/login");
            // 原生ajax需要设置请求头  请求头放在open后 
            xhr.setRequestHeader(
                "content-type",
                "application/x-www-form-urlencoded",
            );
            // 4 显示数据
            xhr.send(`username=123&password=123`);
        };
    </script>
</body>
</html>